package com.example.transmit;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.Data;

/**
 * 计时时钟，可用于线程池中。需要线程池支持TransmittableThreadLocal
 */
public class StopWatch {
    private static TransmittableThreadLocal<ClockInfo> clocks = new TransmittableThreadLocal<>();

    public static void start() {
        ClockInfo clockInfo = new ClockInfo();
        clocks.set(clockInfo);
    }

    public static void stop() {
        ClockInfo clockInfo = clocks.get();
        if (clockInfo.endTime == 0) {
            clockInfo.endTime = TimeUtil.nowMilliSecond();
//            clocks.set(clockInfo);
        }
    }

    public static void remove() {
        clocks.remove();
    }

    /**
     * 返回总的耗时时间，单位毫秒
     * @return 时钟未开始或未停止返回-1
     */
    public static long getTotalTimeMillis() {
        ClockInfo clockInfo = clocks.get();
        if (clockInfo == null) {
            return -1;
        }
        if (clockInfo.getStartTime() == 0) {
            return -1;
        }
        if (clockInfo.getEndTime() == 0) {
            return -1;
        }
        return clockInfo.getEndTime() - clockInfo.getStartTime();
    }

    @Data
    private static class ClockInfo {
        private long startTime = 0;
        private long endTime = 0;
        public ClockInfo() {
            startTime = TimeUtil.nowMilliSecond();
        }
    }
}
